<template>
  <div class="add_project_page" v-loading="pageLoading">
    <div class="fail_mod" v-if="this.id">
      <img src="@/assets/icons/fail_status.png" alt="" class="icon">
      <div class="reason_box">
        <span class="reason">驳回原因：</span>
        <span class="text">企业信息与法人信息不一致，法人身份证附件</span>
      </div>
    </div>
    <el-form ref="projectForm" :model="projectForm" :rules="projectRules" label-position="right" label-width="140px">
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">项目公司</h5>
          </div>
        </div>
        <div>
          <el-row class="row">
            <el-col :span="8">
              <el-form-item label="企业名称" prop="enterpriseName">
                <el-input v-model="projectForm.enterpriseName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码" prop="creditCode">
                <el-input v-model="projectForm.creditCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法定代表人" prop="legal">
                <el-input v-model="projectForm.legal"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="8">
              <el-form-item label="法定代表人电话" prop="frContactPhone">
                <el-input v-model="projectForm.frContactPhone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务联系人姓名" prop="bsContactName">
                <el-input v-model="projectForm.bsContactName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务联系人电话" prop="bsContactPhone">
                <el-input v-model="projectForm.bsContactPhone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">项目信息</h5>
          </div>
        </div>
        <div>
          <el-row class="row">
            <el-col :span="8">
              <el-form-item label="项目名称" prop="pname">
                <el-input v-model="projectForm.pname"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目编号" prop="pcode">
                <el-input v-model="projectForm.pcode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目金额(元)" prop="pamount">
                <el-input v-model="projectForm.pamount"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="8">
              <el-form-item label="项目状态" prop="pstatus">
                <el-select v-model="projectForm.pstatus" style="width: 100%;">
                  <el-option
                    v-for="item in projectStatusList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目签署日期" prop="psignDate">
                <el-date-picker
                  v-model="projectForm.psignDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目交付日期" prop="pdeliverDate">
                <el-date-picker
                  v-model="projectForm.pdeliverDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div class="mod">
      <div class="title_box">
        <div class="title">
          <i class="icon"></i>
          <h5 class="name">最新贸易合同</h5>
        </div>
        <div class="tips">
          <div><span class="important">贸易合同</span>请上传PDF格式贸易合同文件</div>
          <el-form ref="newContractForm" :model="newContractForm" :rules="newContractRules">
            <el-form-item prop="newContractInfo" label-width="0">
              <el-button type="primary" class="upload_btn" :loading="newContractLoading">
                上传合同
                <input type="file" accept="application/pdf" class="upload_input" @change="uploadNewContract" />
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table :data="newContractForm.newContractInfo" border>
        <el-table-column
          label="序号"
          type="index"
        >
        </el-table-column>
        <el-table-column
          v-for="(item, index) in contractColumns"
          :key="item.label"
          v-bind="item"
        >
          <template slot-scope="scope">
            <el-form ref="newContractTableCell" :model="scope.row">
              <el-form-item
                v-if="item.type === 'date'"
                :prop="item.prop"
                label-width="0"
                style="margin-bottom: 20px;"
                :rules="tableCellRules(item.label, 'date')"
              >
                <el-date-picker
                  v-model="scope.row[item.prop]"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
              <el-form-item
                v-else
                :prop="item.prop"
                label-width="0"
                style="margin-bottom: 20px;"
                :rules="tableCellRules(item.label, 'input')"
              >
                <el-input  v-model="scope.row[item.prop]"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text">
              <a :href="baseURL + scope.row.url" target="_blank">预览</a>
            </el-button>
            <el-button type="text" @click="delNewContractRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="mod">
      <div class="title_box">
        <div class="title">
          <i class="icon"></i>
          <h5 class="name">最新贸易发票</h5>
        </div>
        <div class="tips">
          <div><span class="important">贸易发票</span>请上传JPG、PNG格式贸易发票文件</div>
          <el-form ref="newInvoiceForm" :model="newInvoiceForm" :rules="newInvoiceRules">
            <el-form-item prop="newInvoiceInfo" label-width="0">
              <el-button type="primary" class="upload_btn" :loading="newInvoiceLoading">
                上传发票
                <input type="file" accept="image/jpg,image/png" class="upload_input" @change="ocrNewInvoice" />
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table :data="newInvoiceForm.newInvoiceInfo" border>
        <el-table-column
          v-for="item in invoiceColumns"
          :key="item.label"
          v-bind="item"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="previewBigImg(scope.row.url)">预览</el-button>
            <el-button type="text" @click="delNewInvoiceRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="total_box">
        共计发票金额：<span class="total">{{ newInvoiceForm.newInvoiceTotalAmount }}</span>
      </div>
    </div>
    <div class="mod">
      <div class="title_box">
        <div class="title">
          <i class="icon"></i>
          <h5 class="name">最新其他资料</h5>
          <div class="desc">
            <i class="warn_icon el-icon-warning"></i>
            如果有相应资料或文件可以上传添加
          </div>
        </div>
        <div class="tips">
          <el-button type="primary" class="upload_btn" :loading="newOthersLoading">
            新增资料
            <input type="file" accept="image/jpg,image/png,application/pdf" class="upload_input" @change="uploadNewOthers" />
          </el-button>
        </div>
      </div>
      <el-table :data="newOtherForm.newOtherInfo" border>
        <el-table-column label="序号" type="index" width="200px"></el-table-column>
        <el-table-column
          v-for="item in otherColumns"
          :key="item.label"
          :label="item.label"
          :proop="item.prop"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row[item.prop]"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text">
              <a :href="baseURL + scope.row.url" target="_blank">查看</a>
            </el-button>
            <el-button type="text" @click="delNewOtherRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-form ref="historyForm" :model="historyForm" :rules="historyRules" label-position="right" label-width="140px">
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">历史合作信息</h5>
          </div>
        </div>
        <div>
          <el-row class="row">
            <el-col :span="8">
              <el-form-item label="是否有历史合作" prop="cooperateType">
                <el-radio-group v-model="historyForm.cooperateType">
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="historyForm.cooperateType === '0'">
              <el-form-item label="最早合作签订日期" prop="earliestSignDate">
                <el-date-picker
                  v-model="historyForm.earliestSignDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="historyForm.cooperateType === '0'">
              <el-form-item label="最后合作签订日期" prop="latestSignDate">
                <el-date-picker
                  v-model="historyForm.latestSignDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row" v-if="historyForm.cooperateType === '0'">
            <el-col :span="8">
              <el-form-item label="共计合作年限" prop="cooperationPeriod">
                <el-input v-model="historyForm.cooperationPeriod"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div v-if="historyForm.cooperateType === '0'">
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">贸易合同</h5>
          </div>
          <div class="tips">
            <div><span class="important">贸易合同</span>请上传PDF格式贸易合同文件</div>
            <el-form ref="contractForm" :model="contractForm" :rules="contractRules">
              <el-form-item prop="contractInfo" label-width="0">
                <el-button type="primary" class="upload_btn" :loading="contractLoading">
                  上传合同
                  <input type="file" accept="application/pdf" class="upload_input" @change="uploadContract" />
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-table :data="contractForm.contractInfo" border>
          <el-table-column
            label="序号"
            type="index"
          >
          </el-table-column>
          <el-table-column
            v-for="(item, index) in contractColumns"
            :key="item.label"
            v-bind="item"
          >
            <template slot-scope="scope">
              <el-form ref="contractTableCell" :model="scope.row">
                <el-form-item
                  v-if="item.type === 'date'"
                  :prop="item.prop"
                  label-width="0"
                  style="margin-bottom: 20px;"
                  :rules="tableCellRules(item.label, 'date')"
                >
                  <el-date-picker
                    v-model="scope.row[item.prop]"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item
                  v-else
                  :prop="item.prop"
                  label-width="0"
                  style="margin-bottom: 20px;"
                  :rules="tableCellRules(item.label, 'input')"
                >
                  <el-input  v-model="scope.row[item.prop]"></el-input>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text">
                <a :href="baseURL + scope.row.url" target="_blank">预览</a>
              </el-button>
              <el-button type="text" @click="delContractRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">贸易发票</h5>
          </div>
          <div class="tips">
            <div><span class="important">贸易发票</span>请上传JPG、PNG格式贸易发票文件</div>
            <el-form ref="invoiceForm" :model="invoiceForm" :rules="invoiceRules">
              <el-form-item prop="invoiceInfo" label-width="0">
                <el-button type="primary" class="upload_btn" :loading="invoiceLoading">
                  上传发票
                  <input type="file" accept="image/jpg,image/png" class="upload_input" @change="ocrInvoice" />
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-table :data="invoiceForm.invoiceInfo" border>
          <el-table-column
            v-for="item in invoiceColumns"
            :key="item.label"
            v-bind="item"
          >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="previewBigImg(scope.row.url)">预览</el-button>
              <el-button type="text" @click="delInvoiceRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="total_box">
          共计发票金额：<span class="total">{{ invoiceForm.invoiceTotalAmount }}</span>
        </div>
      </div>
      <div class="mod">
        <div class="title_box">
          <div class="title">
            <i class="icon"></i>
            <h5 class="name">其他资料</h5>
            <div class="desc">
              <i class="warn_icon el-icon-warning"></i>
              如果有相应资料或文件可以上传添加
            </div>
          </div>
          <div class="tips">
            <el-button type="primary" class="upload_btn" :loading="othersLoading">
              新增资料
              <input type="file" accept="image/jpg,image/png,application/pdf" class="upload_input" @change="uploadOthers" />
            </el-button>
          </div>
        </div>
        <el-table :data="otherForm.otherInfo" border>
          <el-table-column label="序号" type="index" width="200px"></el-table-column>
          <el-table-column
            v-for="item in otherColumns"
            :key="item.label"
            :label="item.label"
            :proop="item.prop"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row[item.prop]"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text">
                <a :href="baseURL + scope.row.url" target="_blank">查看</a>
              </el-button>
              <el-button type="text" @click="delOtherRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="mod">
      <div class="btns">
        <el-button class="btn btn_cancel">取 消</el-button>
        <el-button class="btn" type="primary" :loading="submitLoading" @click="submit">提 交</el-button>
      </div>
    </div>
    <CustomDialog
      title="查看内容"
      width="70%"
      :visible="dialogVisible"
      @close="dialogVisible = false"
    >
      <div class="mask_dialog_content">
        <div class="img_box">
          <img :src="baseURL+ previewBigImgUrl" alt="" class="img" />
        </div>
      </div>
    </CustomDialog>
  </div>
</template>

<script>
import {
  addProject,
  editProject,
  projectDetail,
  uploadFile,
  ocrInvoice
} from '@/api/production'
import CustomDialog from '@/customComponents/dialog'

export default {
  components: {
    CustomDialog,
  },
  data() {
    const validateMobilePhone = (message) => {
      return (rule, value, callback) => {
        if (/^1\d{10}$/.test(value)) {
          callback();
        } else {
          callback(message);
        }
      };
    };
    return {
      pageLoading: false,
      newContractLoading: false,
      newInvoiceLoading: false,
      newOthersLoading: false,
      contractLoading: false,
      invoiceLoading: false,
      othersLoading: false,
      submitLoading: false,
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      contractColumns: [], // 贸易合同列
      contractTableData: [], // 贸易合同数据
      invoiceColumns: [], // 贸易发票列
      invoiceTableData: [], // 贸易发票数据
      id: '', // 项目id
      detailObj: {}, // 项目详情信息
      projectStatusList: [], // 项目状态列表
      projectForm: {
        enterpriseName: '', // 企业名称
        creditCode: '', // 统一社会信用代码
        legal: '', // 法定代表人
        frContactPhone: '', // 法定代表人电话
        bsContactName: '', // 业务联系人姓名
        bsContactPhone: '', // 业务联系人电话
        pname: '', // 项目名称
        pcode: '', // 项目编号
        pamount: '', // 项目金额（元）
        pstatus: '', // 项目状态，字典（p_status）
        psignDate: '', // 项目签署日期
        pdeliverDate: '', // 项目交付日期
      },
      projectRules: {
        enterpriseName: [{ required: true, trigger: ['change', 'blur'], message: '请输入企业名称' }],
        creditCode: [{ required: true, trigger: ['change', 'blur'], message: '请输入统一社会信用代码' }],
        legal: [{ required: true, trigger: ['change', 'blur'], message: '请输入法定代表人' }],
        frContactPhone: [
          { required: true, trigger: ['change', 'blur'], message: '请输入法定代表人电话' },
          {
            validator: validateMobilePhone("请输入正确的法定代表人手机号码"),
            trigger: ["change", "blur"],
          },
        ],
        bsContactName: [{ required: true, trigger: ['change', 'blur'], message: '请输入业务联系人姓名' }],
        bsContactPhone: [
          { required: true, trigger: ['change', 'blur'], message: '请输入业务联系人电话' },
          {
            validator: validateMobilePhone("请输入正确的业务联系人电话"),
            trigger: ["change", "blur"],
          },
        ],
        pname: [{ required: true, trigger: ['change', 'blur'], message: '请输入项目名称' }],
        pcode: [{ required: true, trigger: ['change', 'blur'], message: '请输入项目编号' }],
        pamount: [{ required: true, trigger: ['change', 'blur'], message: '请输入项目金额（元）' }],
        pstatus: [{ required: true, trigger: ['change', 'blur'], message: '请选择项目状态' }],
        psignDate: [{ required: true, trigger: ['change', 'blur'], message: '请输入项目签署日期' }],
        pdeliverDate: [{ required: true, trigger: ['change', 'blur'], message: '请选择项目交付日期' }],
      },
      newContractForm: {
        newContractInfo: [], // 最新项目贸易合同信息
      },
      newContractRules: {
        newContractInfo: [{ required: true, trigger: ['change', 'blur'], message: '请上传最新贸易合同' }]
      },
      newInvoiceForm: {
        newInvoiceInfo: [], // 最新贸易发票json
        newInvoiceTotalAmount: '', // 最新发票总金额
      },
      newInvoiceRules: {
        newInvoiceInfo: [
          {
            validator: (rule, cellValue, callback) => {
              if (cellValue?.length) {
                callback()
              } else {
                callback('请上传最新贸易发票')
              }
            },
          }
        ]
      },
      newOtherForm: {
        newOtherInfo: [], // 最新其他资料
      },
      historyForm: {
        cooperateType: '', // 是否有历史合作 0:是 1:否
        earliestSignDate: '', // 最早合作签订日期
        latestSignDate: '', // 最后合作签订日期
        cooperationPeriod: '', // 共计合作年限
      },
      historyRules: {
        cooperateType: [{ required: true, trigger: ['change', 'blur'], message: '请选择历史合作' }],
        earliestSignDate: [{ required: true, trigger: ['change', 'blur'], message: '请选择最早合作签订日期' }], // 最早合作签订日期
        latestSignDate: [{ required: true, trigger: ['change', 'blur'], message: '请选择最后合作签订日期' }], // 最后合作签订日期
        cooperationPeriod: [{ required: true, trigger: ['change', 'blur'], message: '请选择共计合作年限' }], // 共计合作年限
      },
      contractForm: {
        contractInfo: [], // 项目贸易合同信息
      },
      contractRules: {
        contractInfo: [{ required: true, trigger: ['change', 'blur'], message: '请上传贸易合同' }]
      },
      invoiceForm: {
        invoiceInfo: [], // 贸易发票json
        invoiceTotalAmount: '', // 发票总金额
      },
      invoiceRules: {
        invoiceInfo: [
          {
            validator: (rule, cellValue, callback) => {
              if (cellValue?.length) {
                callback()
              } else {
                callback('请上传发票')
              }
            },
          }
        ]
      },
      otherForm: {
        otherInfo: [], // 其他资料
      },
      dialogVisible: false, // 预览图弹窗
      previewBigImgUrl: '', // 预览图
    }
  },
  created() {
    this.contractColumns = [
      {
        label: '合同名称',
        prop: 'contractName'
      },
      {
        label: '合同编号',
        prop: 'contractCode'
      },
      {
        label: '合同金额',
        prop: 'contractAmount'
      },
      {
        label: '合同签订日期',
        prop: 'contractDateStart',
        type: 'date',
      },
      {
        label: '合同结束日期',
        prop: 'contractDateEnd',
        type: 'date',
      },
    ]
    this.invoiceColumns = [
      {
        label: '序号',
        type: 'index',
      },
      {
        label: '发票类型',
        prop: 'invoiceTypeDesc'
      },
      {
        label: '发票代码',
        prop: 'code'
      },
      {
        label: '发票号码',
        prop: 'no'
      },
      // {
      //   label: '发票校验码',
      //   prop: ''
      // },
      {
        label: '发票金额(元)',
        prop: 'sumAmount'
      },
      {
        label: '开票日期',
        prop: 'date'
      },
      {
        label: '购买方',
        prop: 'buyerName'
      },
      {
        label: '销售方',
        prop: 'sellerName'
      },
    ]
    this.otherColumns = [
      {
        label: '文件名称',
        prop: 'fileName'
      },
    ]
  },
  watch: {
    'newInvoiceForm.newInvoiceInfo': {
      handler: function(newVal, oldVal) {
        console.log(this)
        this.newInvoiceForm.newInvoiceTotalAmount = newVal.reduce((res, value) => {
          return res+= value.sumAmount
        }, 0)
      },
      deep: true,
    },
    'invoiceForm.invoiceInfo': {
      handler: function(newVal, oldVal) {
        this.invoiceForm.invoiceTotalAmount = newVal.reduce((res, value) => {
          return res+= value.sumAmount
        }, 0)
      },
      deep: true,
    }
  },
  mounted() {
    this.getProjectStatusList().then(() => {
      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.getProjectDetail()
      }
    })
  },
  methods: {
    // 获取项目状态列表
    getProjectStatusList() {
      return new Promise((resolove, reject) => {
        this.getDicts('p_status').then((res) => {
          if (res.code === 200) {
            this.projectStatusList = res.data
            resolove()
          } else {
            reject()
          }
        })
      })
    },
    // 获取项目信息
    getProjectDetail() {
      this.pageLoading = true
      projectDetail(this.id).then((res) => {
        this.pageLoading = false
        Object.keys(this.projectForm).forEach((key) => {
          this.projectForm[key] = res.data[key]
        })
        this.newContractForm.newContractInfo = JSON.parse(res.data.newContractInfo || '[]')
        this.newInvoiceForm.newInvoiceInfo = JSON.parse(res.data.newInvoiceInfo || '[]')
        this.newOtherForm.newOtherInfo = JSON.parse(res.data.newOtherInfo || '[]')
        Object.keys(this.historyForm).forEach((key) => {
          this.historyForm[key] = res.data[key]
        })
        this.contractForm.contractInfo = JSON.parse(res.data.contractInfo || '[]')
        this.invoiceForm.invoiceInfo = JSON.parse(res.data.invoiceInfo || '[]')
        this.otherForm.otherInfo = JSON.parse(res.data.otherInfo || '[]')
      }).catch(() => {
        this.pageLoading = false
      })
    },
    // 上传最新贸易合同
    uploadNewContract(e) {
      this.newContractLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      uploadFile({ file }).then((res) => {
        this.newContractLoading = false
        this.newContractForm.newContractInfo = [
          ...this.newContractForm.newContractInfo,
          {
            contractName: '',
            contractCode: '',
            contractAmount: '',
            contractDateStart: '',
            contractDateEnd: '',
            url: res.fileName,
          }
        ]
      }).catch(() => {
        this.newContractLoading = false
      })
    },
    // 删除最新贸易合同
    delNewContractRow(index) {
      this.newContractForm.newContractInfo.splice(index, 1)
      this.$set(this.newContractForm, 'newContractInfo', this.newContractForm.newContractInfo)
    },
    // 最新贸易发票ocr
    ocrNewInvoice(e) {
      this.invoiceLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      ocrInvoice({ file }).then((res) => {
        this.InvoiceLoading = false
        this.newInvoiceForm.newInvoiceInfo = [...this.newInvoiceForm.newInvoiceInfo, { ...res.data.invoice, url: res.data.url }]
      }).catch(() => {
        this.invoiceLoading = false
      })
    },
    // 删除最新贸易发票
    delNewInvoiceRow(index) {
      this.newInvoiceForm.newInvoiceInfo.splice(index, 1)
      this.$forceUpdate()
    },
    // 上传最新其他资料
    uploadNewOthers(e) {
      this.newOthersLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      uploadFile({ file }).then((res) => {
        this.newOthersLoading = false
        this.newOtherForm.newOtherInfo = [
          ...this.newOtherForm.newOtherInfo,
          {
            fileName: '',
            url: res.fileName,
          },
        ]
      }).catch(() => {
        this.newOthersLoading = false
      })
    },
    // 删除最新其他资料
    delNewOtherRow(index) {
      this.newOtherForm.newOtherInfo.splice(index, 1)
      this.$forceUpdate()
    },
    // 上传贸易合同
    uploadContract(e) {
      this.contractLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      uploadFile({ file }).then((res) => {
        this.contractLoading = false
        this.contractForm.contractInfo = [
          ...this.contractForm.contractInfo,
          {
            contractName: '',
            contractCode: '',
            contractAmount: '',
            contractDateStart: '',
            contractDateEnd: '',
            url: res.fileName,
          }
        ]
      }).catch(() => {
        this.contractLoading = false
      })
    },
    // 删除贸易合同
    delContractRow(index) {
      this.contractForm.contractInfo.splice(index, 1)
      this.$set(this.contractForm, 'contractInfo', this.contractForm.contractInfo)
    },
    // 贸易发票ocr
    ocrInvoice(e) {
      this.invoiceLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      ocrInvoice({ file }).then((res) => {
        this.invoiceLoading = false
        this.invoiceForm.invoiceInfo = [...this.invoiceForm.invoiceInfo, { ...res.data.invoice, url: res.data.url }]
      }).catch(() => {
        this.invoiceLoading = false
      })
    },
    // 删除贸易发票
    delInvoiceRow(index) {
      this.invoiceForm.invoiceInfo.splice(index, 1)
      this.$forceUpdate()
    },
    // 上传最新其他资料
    uploadOthers(e) {
      this.othersLoading = true
      const file = e.target.files[0]
      e.target.value = ''
      uploadFile({ file }).then((res) => {
        this.othersLoading = false
        this.otherForm.otherInfo = [
          ...this.otherForm.otherInfo,
          {
            fileName: '',
            url: res.fileName,
          },
        ]
      }).catch(() => {
        this.othersLoading = false
      })
    },
    // 删除其他资料
    delOtherRow(index) {
      this.otherForm.otherInfo.splice(index, 1)
      this.$forceUpdate()
    },
    // 表格中的输入校验规则
    tableCellRules(label, type) {
      const rules = {
        required: true,
        trigger: ['change', 'blur'],
        message: `${type === 'date' ? '请选择' : '请输入'}${label}`
      }
      return rules
    },
    // 预览发票大图
    previewBigImg(url) {
      this.previewBigImgUrl = url
      this.dialogVisible = true
    },
    // this.$refs.projectForm校验
    projectFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.projectForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    //this.$refs.newContractForm校验
    newContractFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.newContractForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // $ref.newContractTableCell 校验，合同表格中的校验
    newContractTableCellValidate() {
      console.log(this.$refs.newContractTableCell)
      const pList = []
      if (this.$refs?.newContractTableCell?.length) {
        this.$refs.newContractTableCell.forEach((ref) => {
          pList.push(new Promise((resolve, reject) => {
            ref.validate((valid) => {
              if (valid) {
                resolve()
              } else {
                reject()
              }
            })
          }))
        })
      }
      return pList
    },
    // this.$refs.newInvoiceForm 校验
    newInvoiceFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.newInvoiceForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject('新发票')
          }
        })
      })
    },
    // this.$refs.historyForm 校验
    historyFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.historyForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    //this.$refs.contractForm校验
    contractFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.contractForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // $ref.contractTableCell 校验，合同表格中的校验
    contractTableCellValidate() {
      console.log(this.$refs.contractTableCell)
      const pList = []
      if (this.$refs?.contractTableCell?.length) {
        this.$refs.contractTableCell.forEach((ref) => {
          pList.push(new Promise((resolve, reject) => {
            ref.validate((valid) => {
              if (valid) {
                resolve()
              } else {
                reject()
              }
            })
          }))
        })
      }
      return pList
    },
    // this.$refs.invoiceForm 校验
    invoiceFormValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.invoiceForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject('老发票')
          }
        })
      })
    },
    submit() {
      const data = {
        ...this.projectForm,
        newContractInfo: JSON.stringify(this.newContractForm.newContractInfo),
        newInvoiceInfo: JSON.stringify(this.newInvoiceForm.newInvoiceInfo),
        newInvoiceTotalAmount: this.newInvoiceForm.newInvoiceTotalAmount,
        newOtherInfo: JSON.stringify(this.newOtherForm.newOtherInfo),
        ...this.historyForm,
        contractInfo: JSON.stringify(this.contractForm.contractInfo),
        invoiceInfo: JSON.stringify(this.invoiceForm.invoiceInfo),
        invoiceTotalAmount: this.invoiceForm.invoiceTotalAmount,
        otherInfo: JSON.stringify(this.otherForm.otherInfo),
      }
      console.log(this.newOtherForm)
      console.log(data)
      this.submitLoading = true
      Promise.all([
        this.projectFormValidate(),
        this.newContractFormValidate(),
        ...this.newContractTableCellValidate(),
        this.newInvoiceFormValidate(),
        this.historyFormValidate(),
        ...(this.historyForm.cooperateType === '0' ? [
          this.contractFormValidate(),
        ...this.contractTableCellValidate(),
        this.invoiceFormValidate(),
     ] : [])

      ]).then(() => {
        let result
        if (this.id) {
          result = editProject(data)
        } else {
          result = addProject(data)
        }
        result.then((res) => {
          this.submitLoading = false
          this.$message({
            type: 'success',
            message: '提交成功',
            onClose: () => {
              this.$router.back()
            }
          })
        }).catch(() => {
          this.submitLoading = false
        })
      }).catch(() => {
        this.submitLoading = false
        this.$message({
          type: 'error',
          message: '有信息未填',
          duration: 3000,
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.add_project_page {
  .fail_mod {
    border: 1px solid #FF4D4F;
    border-radius: 12px;
    padding: 26px 30px;
    background-color: #FFF7F6;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    .icon {
      display: block;
      width: 48px;
      height: 48px;
      margin-right: 10px;
    }
    .reason_box {
      color: #FF4D4F;
      font-weight: 600;
      .reason {
        font-size: 20px;
        margin-right: 8px;
      }
      .text {
        font-size: 14px;
      }
    }
  }
  .mod {
    background-color: #fff;
    box-shadow: 0 1px 2px 0 rgba(1, 24, 70, 0.09);
    border-radius: 6px;
    margin-bottom: 16px;
    padding: 20px 16px 24px;
    .title_box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      .title {
        display: flex;
        align-items: center;
        .icon {
          width: 3px;
          height: 16px;
          border-radius: 1px;
          background-color: $theme;
          margin-right: 5px;
        }
        .name {
          color: #333;
          font-size: 16px;
          font-weight: 600;
        }
        .desc {
          margin-left: 20px;
          color: #F29C1C;
          font-size: 13px;
          .warn_icon {
            font-size: 14px;
            margin-right: 8px;
          }
        }
      }
      .tips {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #777;
        font-size: 14px;
        .important {
          color: $theme;
          margin-right: 4px;
        }
        .upload_btn {
          position: relative;
          margin-left: 24px;
          .upload_input {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 2;
            opacity: 0;
            cursor: pointer;
          }
        }
      }
    }
    ::v-deep .el-form-item {
      margin-bottom: 0;
    }
    ::v-deep .el-form-item--medium .el-form-item__label {
      color: #777;
    }
    .row {
      margin-bottom: 20px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .tips {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      color: #777;
      font-size: 14px;
      .important {
        color: $theme;
        margin-right: 4px;
      }
      .upload_btn {
        position: relative;
        .upload_input {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 2;
          opacity: 0;
          cursor: pointer;
        }
      }
    }
    .total_box {
      height: 32px;
      line-height: 32px;
      background-color: #FFFAF4;
      color: #333;
      font-size: 14px;
      font-weight: 500;
      border-radius: 2px;
      padding-left: 28px;
      margin-top: 20px;
      .total {
        color: #FF4D4F;
        font-size: 20px;
      }
    }
    .btns {
      display: flex;
      justify-content: center;
      align-items: center;
      .btn {
        width: 120px;
      }
      .btn_cancel {
        margin-right: 24px;
      }
    }
  }
}
</style>
